import { ITask, IVector } from "../core/task";
import { DependencyContainer, container, singleton, Disposable, scoped, Lifecycle } from "tsyringe";
import type { AtomicLong, ReentrantLock, Disposable as TDisposable, Thread } from 'threads'
declare const java: any;
@scoped(Lifecycle.ContainerScoped)
export class Task implements ITask, Disposable{
    tasks: Thread[] = [];
    start(cb: (container: DependencyContainer) => void): Thread {
        const task = threads.start(()=>{
            cb(container)
        })
        this.tasks.push(task)
        return task;
    }

    atomic(): AtomicLong {
        const a = threads.atomic()
        return a;
    }

    sync(fn: Function): Function {
        return sync(fn) as Function;
    }

    lock(): ReentrantLock {
        return threads.lock()
    }

    vector(): IVector {
        return new java.util.Vector()
    }

    disposable<T>(): TDisposable {
        return threads.disposable()
    }

    dispose(): void | Promise<void> {
        this.tasks.map(task=>{
            if (task && task.isAlive()) {
                task.interrupt()
            }
        });
        this.tasks = [];
    }
}